/*************************************************************************
	> File Name: 020.有效的括号_v2.c
	> Author: Maureen 
	> Mail: Maureen@qq.com 
	> Created Time: 五  9/ 3 16:19:06 2021
 ************************************************************************/

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

//通过递归使用系统栈

bool judgeOne(char *s, int *i, int d) {
    bool flag = true;
    int j = d;
    //printf("in %d\n", *i);
    while (s[*i] && flag) {
        switch (s[*i]) {
            case '(':
                ++(*i);
                flag = judgeOne(s, i, d + 1);
                if (s[*i] == ')') {
                    ++(*i);
                    flag &= true;
                } else if (s[*i] == ']' || s[*i] == '}' || s[*i] == '\0') {
                    flag = false;
                }
                break;
            case '[':
                ++(*i);
                flag = judgeOne(s, i, d + 1);
                if (s[*i] == ']') {
                    ++(*i);
                    flag &= true;
                } else if (s[*i] == ')' || s[*i] == '}' || s[*i] == '\0') {
                    flag = false;
                }
                break;
            case '{':
                ++(*i);
                flag = judgeOne(s, i, d + 1);
                if (s[*i] == '}') {
                    ++(*i);
                    flag &= true;
                } else if (s[*i] == ')' || s[*i] == ']' || s[*i] == '\0') {
                    flag = false;
                }
                break;
            case ')':
            case ']':
            case '}':
                return j == 0 ? false : true && flag;
            default:
                return false;
        }
    }
    return flag;
}

bool isValid(char *s) {
    int i = 0;
    int len = strlen(s);
    bool flag = true;
    while (i < len && flag) {
        flag &= judgeOne(s, &i, 0);
    }
    return flag;
}

int main() {
    char s[100] = "([]{})()";
    printf("s is valid = %d\n", isValid(s));
    return 0;
}
